﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using eTerm.MsSql.DbProvider;
using System.Web.Script.Serialization;
using System.Reflection;
using System.ComponentModel;

namespace eTerm.Platform.Web
{
    /// <summary>
    /// Class BasePage
    /// </summary>
    public abstract class BasePage:Page
    {

        /// <summary>
        /// 页面编码[权限表].
        /// </summary>
        /// <value>The page code.</value>
        protected virtual string PageCode { get { return string.Empty; } }


        /// <summary>
        /// 当前登录用户.
        /// </summary>
        /// <value>The current user.</value>
        protected SysUser CurrentUser {
            get {
                int UID = int.Parse(HttpContext.Current.User.Identity.Name);
                return SysUser.FirstOrDefault(l => l.UserId == UID);
            }
        }


        /// <summary>
        /// 初始化EasyUI控件CSS
        /// </summary>
        protected virtual void InitEasyUI() { 
            
        }

        /// <summary>
        /// 初始化UI（不论IsPostBack）
        /// </summary>
        protected virtual void InitUI() { 
            
        }


        protected object Get<T>(T model, string propertyName) {
            object value = null;
            string[] propertyLevel = propertyName.Split(new char[] {'.' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string i in propertyLevel) {
                value = (value == null ? model : value).GetType().GetProperty(i).GetValue((value == null ? model : value), null);
            }
            return value;
        }


        /// <summary>
        /// 返回指定枚举值的描述（通过 
        /// <see cref="System.ComponentModel.DescriptionAttribute"/> 指定）。
        /// 如果没有指定描述，则返回枚举常数的名称，没有找到枚举常数则返回枚举值。
        /// </summary>
        /// <param name="value">要获取描述的枚举值。</param>
        /// <returns>指定枚举值的描述。</returns>
        protected string GetDescription(Enum value)
        {
            Type enumType = value.GetType();
            {
                MemberInfo[] mi = value.GetType().GetMember(value.ToString());
                if (mi != null && mi.Length > 0)
                {
                    DescriptionAttribute attr = Attribute.GetCustomAttribute(mi[0], typeof(DescriptionAttribute)) as DescriptionAttribute;
                    if (attr != null)
                    {
                        return attr.Description;
                    }
                }
            }
            return string.Empty;
        }


        /// <summary>
        /// Gets the page loading text.
        /// </summary>
        /// <value>The page loading text.</value>
        protected virtual string PageLoadingText {
            get {
                return @"正在处理";
            }
        }


        protected Attribute GetAttribute(object value,Type attribute) {
            Type enumType = value.GetType();
            {
                MemberInfo[] mi = value.GetType().GetMember(value.ToString());
                if (mi != null && mi.Length > 0)
                {
                    Attribute attr = Attribute.GetCustomAttribute(mi[0], attribute);
                    if (attr != null)
                    {
                        return attr;
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 生成JSON数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        protected string JsonResult(object data) {
            if (data != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                return (serializer.Serialize(data));
            }
            return string.Empty;
        }


        /// <summary>
        /// Gets the UID.
        /// </summary>
        /// <value>The UID.</value>
        protected int UID {
            get {
                return int.Parse(HttpContext.Current.User.Identity.Name);
            }
        }


        /// <summary>
        /// 页面初始化.
        /// </summary>
        protected virtual void InitPageLoad() { 
            
        }


        protected override void OnLoadComplete(EventArgs e)
        {
            base.OnLoadComplete(e);
            InitEasyUI();
        }


        protected override void OnLoad(EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                int UID = int.Parse(HttpContext.Current.User.Identity.Name);
                if (!string.IsNullOrEmpty(PageCode) && !SysUserAuthority.Exists(l => l.UserId == UID && l.AuthorityCode == PageCode))
                    throw new PlatformPageException(PageCode);
                base.OnLoad(e);
                if (!string.IsNullOrEmpty(PageCode))
                {
                    SysAuthority pageInfo = SysAuthority.FirstOrDefault(l => l.AuthorityCode == PageCode);
                    this.Title = string.Format(@"{0}--{1}", pageInfo.AuthorityCode, pageInfo.AuthorityName);
                }
            }
            InitUI();
            if (!IsPostBack)
                InitPageLoad();
        }

        #region BlockUI
        public virtual bool ShowBlockUI
        {
            get
            {
                return true;
            }
        }

        //const string jsOnSubmit = "try{if(typeof(es_xlAspPageOnSubmit) == \"function\" && es_xlAspPageOnSubmit() == false) return false;}catch(e){}";
        //const string jsStartup = "try{if(typeof(es_xlAspPageStartup) == \"function\") es_xlAspPageStartup();}catch(e){}";

        protected override void OnPreRender(EventArgs e)
        {
            if (this.ShowBlockUI)
            {
                    //string JavaScript = @"$.blockUI({message: ""<div style='height:30px;'></div><div><img src='{0}' alt='Progress'/></div><div style='text-align:right;'><img src='{1}' alt='ShinsoftLog'/>&nbsp;</div>""});";
                var js =  "if (typeof(ValidatorOnSubmit) == \"function\" && ValidatorOnSubmit() == false) return false; try{"
                    + string.Format(@"$.jBox.tip(""{0}......"",""loading""); ", PageLoadingText)
                    + "}catch(e){} return true;";
                this.ClientScript.RegisterOnSubmitStatement(this.GetType(), "XLBlockUIForm", js);
                System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "XLBlockUIAjax", "try{$.jBox.closeTip();$.jBox.tip('页面请求已处理完毕。','info');}catch(e){}", true);
            }
            //else
            //{
            //    this.ClientScript.RegisterOnSubmitStatement(this.GetType(), "es_xlAspPageOnSubmit", jsOnSubmit);
            //    System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "es_xlAspPageStartup", jsStartup, true);
            //}

            base.OnPreRender(e);
        }
        #endregion BlockUI

        #region RegisterStartupScript
        protected void BaseRegisterStartupScript<T>(T sender, string key, string script, bool addScriptTags)
        {
            if (sender is UpdatePanel)
                ScriptManager.RegisterStartupScript(sender as UpdatePanel, typeof(T), key, script, addScriptTags);
            else if (sender is Control)
                ScriptManager.RegisterStartupScript(sender as Control, typeof(T), key, script, addScriptTags);
            else if (sender is Page)
                ScriptManager.RegisterStartupScript(sender as Page, typeof(T), key, script, addScriptTags);
        }


        protected Control GetUpdatePanel(string pnlContent) {
            return this.Master.FindControl(pnlContent);
        }
        #endregion

    }


    public class PlatformPageException : Exception {
        public string PageCode { get; private set; }
        public PlatformPageException(string PageCode):base(string.Format(@"用户无权访问该页面{0}，请确认页面已被授权。",PageCode)) {
            this.PageCode = PageCode;
        }
    }

}
